<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FTP同步</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <style>

        .model {
            display: none;
            position: fixed;
            z-index: 1;
            padding-top: 100px;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }
        /* 弹窗内容 */
        .model-content{
            position: relative;
            background-color: #fefefe;
            margin: auto;
            padding: 0;
            border: 1px solid #888;
            border-radius: 20px;
            width: 35%;
            height: 30%;
            box-shadow: 0 4px 8px 0 black, 0 6px 20px 0 black;
            animation: animate_top 0.4s
        }
        .history-content{
            position: relative;
            background-color: #fefefe;
            margin: auto;
            padding: 0;
            border: 1px solid #888;
            border-radius: 20px;
            width: 55%;
            height: 85%;
            overflow: hidden;
            box-shadow: 0 4px 8px 0 black, 0 6px 20px 0 black;
            animation: animate_top 0.4s
        }
        /* 添加动画 */
        @keyframes animate_top {
            from {
                top: -300px;
                opacity: 0
            }
            to {
                top: 0;
                opacity: 1
            }
        }
        #showConfirmBtn:hover, #showCancelBtn:hover, #historyBtn:hover {
            color: #5b88b4;
            text-decoration: none;
            cursor: pointer;
        }
        .model-header {
            color: #5b88b4;
            position: absolute;
            top:5px;left: 5%;
        }
        .model-body {
            position: absolute;
            top: 40%;
            left: 10%;
        }
        .history-body {
            position: absolute;
            top: 10%;
            left: 10%;
            right: 10%;
        }
        .model-footer {
            text-align: right;
            color: #409eff;
            position: absolute;
            top: 83%;
            right: 5%;
        }
    </style>
</head>
<body>
    <div style="text-align: right">
        <span style="font-size: 20px">欢迎{{ username }}</span>
        <button id="log" onclick="getLogs()">查看同步历史</button>
    </div>
    <div style="text-align: center">
        <h1>ftp同步</h1>
    </div>
    <div style="text-align: center">
        <span>同步模式:</span>
        <select id="mode">
            <option value="1">本地为主同步</option>
            <option value="2">服务端为主同步</option>
            <option value="0">双向同步</option>
        </select>
        <span>扫描时间:</span>
        <select id="interval">
            <option value="10">10s</option>
            <option value="30">30s</option>
            <option value="60">60s</option>
        </select>
        <button class="btn-default" onclick="refresh()">立即扫描</button>
        <button class="btn-default" onclick="add_folder()">添加同步目录</button>
    </div>

    <button class="btn-info" onclick="toFather(now)">返回</button>

    <div id="file_table" style="text-align: center">
        <table border="1" width="75%" align="center">
            <tr>
                <th>同步目录</th>
                <th>文件大小</th>
                <th>同步状态</th>
                <th>开始/暂停同步</th>
                <th>删除目录</th>
            </tr>
        {% for ftp_file in ftp_files %}
            <tr id="{{ ftp_file }}">
                <td style="cursor: pointer" onclick="toChild('{{ ftp_file }}')">{{ ftp_file }}</td>
                <td id="{{ ftp_file }}_2" onclick="get_size('{{ ftp_file }}')" style="cursor: pointer">{{ ftp_files_size[ftp_file] }}kb</td>
            {% if ftp_files_status[ftp_file] == True %}
                <td id="{{ ftp_file }}_3" onclick="get_status('{{ ftp_file }}')" style="cursor: pointer">已同步</td>
            {% elif ftp_files_status[ftp_file] == False %}
                <td id="{{ ftp_file }}_3" onclick="get_status('{{ ftp_file }}')" style="cursor: pointer">未同步</td>
            {% endif %}
            {% if ftp_file in current_files %}
                <td><button id="{{ ftp_file }}_4" onclick="remove_current('{{ ftp_file }}')" class="btn-default">暂停</button></td>
            {% else %}
                <td><button id="{{ ftp_file }}_4" onclick="add_current('{{ ftp_file }}')" class="btn-default">开始</button></td>
            {% endif %}
                <td><button onclick="delete_dirs('{{ ftp_file }}')">删除</button></td>
            </tr>
        {% endfor %}
        </table>
    </div>
    <button class="btn-default" id="openIgnoreBtn" onclick="to_ignore()">忽略文件列表</button>
    <div id="myModel" class="model">
        <div class="model-content">
            <div id="model-header" class="model-header">请输入新建目录名</div>
            <div id="model-body" class="model-body">
                <input id="folder" type="text" class="form-control">
                <div>
                  <span id="local_folder" style="display: none"></span>
                </div>
            </div>
            <div class="model-footer">
                <span id="showConfirmBtn" onclick="confirm()" style="cursor: pointer">确认</span>
                <span id="showCancelBtn" onclick="cancel()" style="cursor: pointer">取消</span>
            </div>
        </div>
    </div>
    <div id="history" class="model" style="display: none">
        <div class="history-content">
            <div id="history-header" class="model-header">同步历史</div>
            <div id="history-body" class="history-body">
                <table id="history_table" border="1" width="100%" align="center">

                </table>
            </div>
            <div class="model-footer">
                <span id="historyBtn" style="cursor: pointer">确认</span>
            </div>
        </div>
    </div>
    <div id="ignore" class="model" style="display: none">
        <div class="model-content">
            <div id="ignore-header" class="model-header">忽略列表</div>
            <div id="ignore-body" class="model-body">

            </div>
            <div class="model-footer">
                <span id="ignoreBtn" style="cursor: pointer">确认</span>
            </div>
        </div>
    </div>
{#    <img id="preview" src="" />#}
{#    <input type="file" name="file1" id="preview_file" />#}
</body>


<script>
    let mode = '1'; //模式
    let interval = '10'; //扫描时间

    window.onload = function (){
        $.ajax({
            url:'/interval/get/',
            method:'POST',
            success:function (data){
                let obj = JSON.parse(data)
                    if (obj.code === '1') {
                        $('#interval').children().each(function (){
                            if (obj.data.toString() === this.value.toString()){
                                this.selected = true
                            }
                        })
                    }
            }
        })
        $.ajax({
            url:'/mode/get/',
            method:'POST',
            success:function (data){
                let obj = JSON.parse(data)
                    if (obj.code === '1') {
                        $('#mode').children().each(function (){
                            if (obj.data.toString() === this.value.toString()){
                                this.selected = true
                            }
                        })
                    }
            }
        })
    }

    function refresh(){
        $.ajax({
            url:'/refresh/',
            method:'POST',
            success:function (data) {
                let obj = JSON.parse(data)
                    if (obj.code === '1') {
                        console.log('扫描成功')
                    }
            }
        })

    }
    $("#mode").change(function (){
        let m = $("#mode").val()
        if (m !== mode){
            mode = m
            //设置模式
            $.ajax({
                url:'/config/mode/',
                method:'GET',
                data:{
                    'mode':mode
                },
                success:function (data){
                    let obj = JSON.parse(data)
                    if (obj.code === '1') {
                        console.log('同步模式修改成功:' + mode)
                    }
                }
            })
        }
    })

    $("#interval").change(function (){
        let s = $("#interval").val()
        if (s !== interval){
            interval = s
            //设置扫描时间
            $.ajax({
                url:'/config/interval/',
                method:'GET',
                data:{
                    'interval':interval
                },
                success:function (data){
                    let obj = JSON.parse(data)
                    if (obj.code === '1'){
                        console.log('扫描时间修改成功:'+interval+'s')
                    }
                }
            })
        }
    })
    //当前所在页面路径
    let now  = ''
    function toChild(file){
        if (file === ''){
            window.location.reload()
            return
        }
        let shu
        $.ajax({
                url:'/files/get/',
                method:'POST',
                data:{
                    'file':file
                },
                success:function (data){
                    let obj = JSON.parse(data)
                    console.log(obj.msg)
                    if (obj.code === '1') {
                        now = file
                        shu =  obj.data.replace('[','').replace(']','').replaceAll('\'','').split(',')
                        console.log(shu)
                        $('#file_table').html('')
                        let fatherNode = document.getElementById('file_table')
                        let table = document.createElement("table")
                        let tbody = document.createElement('tbody')
                        table.appendChild(tbody)
                        table.border = '1'
                        table.width = '75%'
                        table.align = 'center'
                        fatherNode.appendChild(table)
                        let tr1 = document.createElement("tr")
                        let th1 = document.createElement("th")
                        let th2 = document.createElement("th")
                        th1.innerHTML = '文件名'
                        th2.innerHTML = '忽略同步'
                        tr1.appendChild(th1)
                        tr1.appendChild(th2)
                        tbody.appendChild(tr1)
                        if (shu.length === 1 && shu[0] === '')
                        {
                            return
                        }
                        for (let i = 0; i < shu.length; i++) {
                            let newNode=document.createElement("td");
                            let td = document.createElement('td')
                            let btn = document.createElement('button')
                            btn.innerHTML = '忽略'
                            td.appendChild(btn)
                            let zu = shu[i].split('/')
                            let last = zu[zu.length - 1]
                            newNode.innerText = last
                            let path = (file+'/'+last).replaceAll('/ ','/')
                            newNode.setAttribute('onclick','toChild(\''+ path +'\')')
                            newNode.setAttribute('style','cursor: pointer')
                            btn.setAttribute('onclick','add_ignore(\'/'+ path +'\')')
                            let tr = document.createElement("tr")
                            tr.appendChild(newNode)
                            tr.appendChild(td)
                            tr.id = path.replaceAll('/','_')
                            tbody.appendChild(tr)
                        }
                    }
                }
            })
    }

    function toFather(file){
        let num = file.split('/')
        let temp = ''
        for (let i = 0; i < num.length - 1; i++) {
            temp = temp + '/' + num[i]
        }
        now = temp
        if (now.charAt(0) === '/'){
            now = now.slice(1)
        }
        toChild(now)
    }
    function add_ignore(ignore){
        $.ajax({
            url:'/ignore/add/',
            method:'POST',
            data:{
                'file':ignore
            },
            success:function (data){
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log('忽略文件'+ignore+'成功')
                    toChild(now)
                }
            }
        })
    }
    function remove_ignore(ignore){
        $.ajax({
            url:'/ignore/remove/',
            method:'POST',
            data:{
                'file':ignore
            },
            success:function (data){
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log('取消忽略文件'+ignore+'成功')
                    to_ignore()
                    toChild(now)
                }
            }
        })
    }
    function add_current(file){
        $.ajax({
            url:'/current/add/',
            method:'POST',
            data:{
                    'file':file
            },
            success:function (data){
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log(file+'目录开始同步')
                    let f = $('#'+file+'_4')
                    f.html('暂停')
                    f.attr('onclick','remove_current(\''+file+'\')')
                }
            }
        })
    }
    function remove_current(file){
        $.ajax({
            url:'/current/remove/',
            method:'POST',
            data:{
                    'file':file
            },
            success:function (data){
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log(file+'目录暂停同步')
                    let f = $('#'+file+'_4')
                    f.html('开始')
                    f.attr('onclick','add_current(\''+file+'\')')
                }
            }
        })
    }
    function delete_dirs(file) {
        $.ajax({
            url:'/dir/delete/',
            method:'POST',
            data:{
                'file':file
            },
            success:function (data){
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log(file+'目录删除成功')
                    let f = $('#'+file)
                    f.remove()
                }
            }
        })
    }
    function get_size(file) {
        $.ajax({
            url:'/get/size/',
            method:'POST',
            data:{
                'file':file
            },
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    let f = $('#'+file+'_2')
                    let size = parseInt((obj.data/1024).toString())
                    f.html(size+'kb')
                }
            }
        })
    }
    function get_status(file) {
        $.ajax({
            url:'/get/status/',
            method:'POST',
            data:{
                'file':file
            },
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log(obj)
                    let f = $('#'+file+'_3')
                    let status = obj.data
                    if(status){
                        f.html('已同步')
                    }
                    else {
                        f.html('未同步')
                    }
                }
            }
        })
    }
    function add_folder(){
        $('#myModel').css('display','block')
    }
    let flag = 0
    $('#folder').change(function (){
        $('#local_folder').html($('#folder').val())
    })
    let ftp_file
    function confirm(){
        if(flag === 0){
            ftp_file = $('#folder').val().trim()
            $.ajax({
            url:'/dir/add/',
            method:'POST',
            data:{
                'file':ftp_file
            },
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    $('#local_folder').css('display','block')
                    $('#model-header').html('可绑定本地目录')
                    $('#showCancelBtn').css('display','none')
                    flag = 1
                }
                else {
                    $('#model-header').html('请输入新建目录名(已存在该目录)')
                }
            }})
        }
        else if (flag === 1){
            let local_folder = $('#folder').val().trim()
            console.log(local_folder,ftp_file)
            $.ajax({
            url:'/add/local/dir/',
            method:'POST',
            data:{
                'local_file':local_folder,
                'ftp_file':ftp_file
            },
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    $('#model-header').html('请输入新建目录名')
                    $('#myModel').css('display','none')
                    $('#showCancelBtn').css('display','inline')
                    $('#local_folder').css('display','none')
                    flag = 0
                    $('#folder').val('')
                }
            }})
        }
    }
    function cancel(){
        $('#model-header').html('请输入新建目录名')
        $('#myModel').css('display','none')
        flag = 0
    }
    function getObjectURL(file) {
        let url = null;
        if (window.createObjcectURL !== undefined) {
            url = window.createOjcectURL(file);
        } else if (window.URL !== undefined) {
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL !== undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
    //图片预览
    $("#preview_file").change(function(){
        let file = this.files[0];
        let url = getObjectURL(file);
        console.log(url)
        $('#preview')[0].src = url

    });

    $('#log').click(function () {
        $('#history').css('display','block')
    })

    function getLogs(){
        let history_logs = []
        $.ajax({
            url:'/logs/get/',
            method:'POST',
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1') {
                    let header = document.createElement('tr')
                    header.id = 'header'
                    let header_th = document.createElement('th')
                    header_th.align = 'center'
                    header_th.innerHTML = '操作、文件类型、路径、时间'
                    header.appendChild(header_th)
                    let history_table = document.getElementById('history_table')
                    $('#history_table').html('')
                    history_table.appendChild(header)
                    let logs = obj.data.replace('[','').replace(']','').split('), (')
                    for (let i = 0; i < logs.length; i++) {
                        let logi = logs[i].replace('(','').replace(')','').replaceAll('\'','').split(', ')
                        let log = {}
                        log.filename = logi[0].toString()
                        log.flag = parseInt(logi[1])
                        log.time = logi[2].toString()
                        log.path = logi[3].toString()
                        log.method = parseInt(logi[4])
                        history_logs.push(log)
                        let tr = document.createElement('tr')
                        let td = document.createElement('td')
                        let text = ''
                        if (log.method === 0){
                            text = text + '修改'
                        }else if (log.method === -1){
                            text = text + '删除'
                        }else if (log.method === 1){
                            text = text + '新增'
                        }
                        if (log.flag === 1){
                            text = text + 'ftp'
                        }else if(log.flag === 0) {
                            text = text + '本地'
                        }
                        if (log.filename.includes('.')){
                            text = text + '文件: ' + log.filename
                        }else {
                            text = text + '目录: ' + log.filename
                        }
                        text = text + ' 路径: ' + log.path + ' '
                        text = text + ' 时间: ' + log.time
                        td.innerHTML = text
                        tr.appendChild(td)
                        header.after(tr)
                    }
                }
            }
        })
    }
    $('#historyBtn').click(function (){
        $('#history').css('display','none')
    })
    function to_ignore(){
        $.ajax({
            url:'/ignore/get/',
            method:'POST',
            success:function (data) {
                let obj = JSON.parse(data)
                if (obj.code === '1'){
                    console.log(obj.data)
                    let ignore_list = obj.data.replace('[','').replace(']','').split(', ')
                    let body = document.getElementById('ignore-body')
                    $('#ignore-body').html('')
                    if (ignore_list.length === 1 && ignore_list[0] === ''){
                        return
                    }
                    for (let i = 0; i < ignore_list.length; i++) {
                        let node = document.createElement('div')
                        node.id = ignore_list[i].replaceAll('/','_') + '.ignore'
                        let div = document.createElement('span')
                        div.innerHTML = ignore_list[i]
                        let span = document.createElement('span')
                        span.setAttribute('class','glyphicon glyphicon-remove')
                        span.style.left = '10px'
                        span.style.cursor = 'pointer'
                        span.setAttribute('onclick','remove_ignore('+ ignore_list[i] +')')
                        node.appendChild(div)
                        node.appendChild(span)
                        body.appendChild(node)
                    }
                }
            }
        })
        $('#ignore').css('display','block')
    }
    $('#ignoreBtn').click(function (){
        $('#ignore').css('display','none')
    })
</script>


</html>